package com.arvato.common.https;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * http客户端
 * 
 * 
 * 2015年11月7日 @author wpf
 */
public class HttpUtil {

	private static Logger log = LoggerFactory.getLogger(HttpUtil.class);

	/**
	 * 以post方式提交数据
	 * 
	 * @param url
	 * @param params
	 * @return
	 */
	public static String doPost(String url, Map<String, String> params) {
		log.info("---create http-post:---" + url);
		CloseableHttpClient httpClient = HttpClients.createDefault();
		String body = null;
		try {
			HttpPost post = postForm(url, params);
			body = invoke(httpClient, post);
		} catch (Exception e) {
			throw new RuntimeException("调用doPost出错", e);
		}
		return body;
	}

	/**
	 * get请求
	 * 
	 * @param url
	 * @return
	 */
	public static String doGet(String url) {
		log.info("---create http-get:---" + url);
		CloseableHttpClient httpClient = HttpClients.createDefault();
		String body = null;
		try {
			log.info((new StringBuilder()).append("create http get:")
					.append(url).toString());
			HttpGet get = new HttpGet(url);
			body = invoke(httpClient, get);
		} catch (Exception e) {
			throw new RuntimeException("调用doGet出错", e);
		}
		return body;
	}

	/**
	 * post请求
	 * 
	 * @param url
	 * @param params
	 * @return
	 */
	private static HttpPost postForm(String url, Map<String, String> params) {
		HttpPost httppost = new HttpPost(url);
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();

		Set<String> keySet = params.keySet();
		for (String key : keySet) {
			nvps.add(new BasicNameValuePair(key, params.get(key)));
		}

		try {
			log.info("set utf-8 form entity to httppost");
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nvps,
					"UTF-8");
			// entity.setContentType("application/json");
			httppost.setEntity(entity);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("post方式封装数据发生异常", e);
		}
		return httppost;
	}

	private static String invoke(CloseableHttpClient httpclient,
			HttpUriRequest httppost) {
		CloseableHttpResponse response = sendRequest(httpclient, httppost);
		String body = paseResponse(response);
		return body;
	}

	private static String paseResponse(CloseableHttpResponse response) {
		log.info("get response from http server..");
		HttpEntity entity = response.getEntity();
		log.info((new StringBuilder()).append("response status: ")
				.append(response.getStatusLine()).toString());
		String body = null;
		try {
			body = EntityUtils.toString(entity);
			log.info((new StringBuilder()).append("---body--").append(body)
					.toString());
		} catch (Exception e) {
			throw new RuntimeException("解析httpResponse出错", e);
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				log.error("关闭HttpResponse出错", e);
			}
		}
		return body;
	}

	private static CloseableHttpResponse sendRequest(
			CloseableHttpClient httpclient, HttpUriRequest httpost) {
		log.info("---execute http request...");
		CloseableHttpResponse response = null;
		try {
			response = httpclient.execute(httpost);
			log.info("http response return");
		} catch (Exception e) {
			throw new RuntimeException("执行http请求发生异常", e);
		}
		return response;
	}

	/**
	 * 以json方式通过http psot发送请求
	 * 
	 * @param url
	 * @param source
	 * @return
	 */
	public static String doPostJsonData(String url, Object source) {
		log.info("invoke doPostJsonData");
		String formStatusData = JSON.toJSONString(source);
		CloseableHttpClient httpClient = HttpClients.createDefault();
		StringEntity params = new StringEntity(formStatusData, "UTF-8");
		HttpPost request = new HttpPost(url);
		try {
			request.addHeader("content-type", "application/json");
			request.setEntity(params);
			return invoke(httpClient, request);
		} catch (Exception e) {
			throw new RuntimeException("调用doPostJsonData出错", e);
		}
	}

}
